package com.umgsai.flink.kafka.demo.core;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class StreamWordCount {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment executionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment();
        // 设置并行度，默认为CPU核数
        executionEnvironment.setParallelism(4);
        String inputPath = "src/main/resources/word.txt";
        DataStreamSource<String> dataStreamSource = executionEnvironment.readTextFile(inputPath);
        SingleOutputStreamOperator<Tuple2<String, Integer>> singleOutputStreamOperator = dataStreamSource.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
                // 按空格分词
                String[] words = s.split(" ");
                for (String word : words) {
                    // 每个单词1次
                    Tuple2<String, Integer> tuple2 = Tuple2.of(word, 1);
                    collector.collect(tuple2);
                }
            }
        }).keyBy(0)//按Tuple2中的第1个字段分类
                .sum(1);//按Tuple2中的第2个字段相加
        singleOutputStreamOperator.print();
        singleOutputStreamOperator.executeAndCollect();
    }
}
